package com.yuanxiao.Resovel;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
@Configuration
public class MyLocaleResovel implements LocaleResolver {
    //自定义区域解析器
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        //获取页面手动传递的语言参数值
        String l = httpServletRequest.getParameter("l");
        Locale locale=null;
        if(!StringUtils.isEmpty(l)){
           //如果参数不为空,就根据参数值进行手动语言切换
            String[] s = l.split("_");
            locale = new Locale(s[0], s[1]);
        }else {
            //Accept-Language
            //zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
            String header = httpServletRequest.getHeader("Accept-Language");
            String[] split = header.split(",");
            String[] s = split[0].split("-");
            locale= new Locale(s[0], s[1]);

        }


        return locale;
    }
    //将自定义的MyLocaleResovel重新注册成一个类型为LocaleResolver的bean组件
    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResovel();
    }
}
